package com.example.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.example.service.SysTaskService;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

@TableName("sys_task")
public class SysTask extends SysEntity<SysTask> implements Delayed {

    @TableField("server_key")
    private String serverKey;

    @TableField("failures")
    private int failures = 0;

    @TableField("error_message")
    private String errorMessage;

    @TableField("join_time")
    private Long joinTime;

    @TableField("run_time")
    private Long runTime;

    @TableField("speedy")
    private Boolean speedy = Boolean.FALSE;

    @TableField("success")
    private Boolean success = Boolean.FALSE;

    @TableField("queue_type")
    private Boolean queueType = Boolean.TRUE;

    public String getServerKey() {
        return serverKey;
    }

    public void setServerKey(String serverKey) {
        this.serverKey = serverKey;
    }

    public int getFailures() {
        return failures;
    }

    public void setFailures(int failures) {
        this.failures = failures;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public Long getJoinTime() {
        return joinTime;
    }

    public void setJoinTime(Long joinTime) {
        this.joinTime = joinTime;
    }

    public Boolean getSpeedy() {
        return speedy;
    }

    public void setSpeedy(Boolean speedy) {
        this.speedy = speedy;
    }

    public Boolean getSuccess() {
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    public Boolean getQueueType() {
        return queueType;
    }

    public void setQueueType(Boolean queueType) {
        this.queueType = queueType;
    }


    public Long getRunTime() {
        return runTime;
    }

    public void setRunTime(Long runTime) {
        this.runTime = runTime;
    }

    /**
     * 获取剩余时间
     *
     * @param unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return TimeUnit.NANOSECONDS.convert(failures * SysTaskService.SLEEP_TIME, TimeUnit.MILLISECONDS) + this.runTime - System.nanoTime();
    }

    @Override
    public int compareTo(Delayed o) {
        long rtn = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        if (rtn == 0) {
            return 0;
        } else if (rtn > 0) {
            return 1;
        } else {
            return -1;
        }
    }
}
